package jh.com.jhappbf.usermanager;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.ab.activity.AbActivity;
import com.ab.fragment.AbLoadDialogFragment;
import com.ab.util.AbDialogUtil;
import com.ab.view.titlebar.AbTitleBar;
import com.android.volley.Request.Priority;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.baoyz.swipemenulistview.SwipeMenuListView.OnMenuItemClickListener;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import androidx.core.content.ContextCompat;
import jh.com.jhappbf.R;
import jh.com.jhappbf.httputils.VolleyCallWebService;
import jh.com.jhappbf.httputils.VolleySingleton;
import jh.com.jhappbf.model.UserModel;
import jh.com.jhappbf.ui.State;
import jh.com.jhappbf.utils.JsonHelper;
import jh.com.jhappbf.utils.PixAndDpUtil;

/**
 * @author Administrator
 */
public class UserManagerQuery extends AbActivity implements OnMenuItemClickListener {
    private List<JSONObject> mData;
    private MyBaseAdapter mAdapter;
    private View mContentView;
    private View mErrorView;
    private Context mAppContext;
    private final int ADDUSER = 0X001;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContentView = getLayoutInflater().inflate(R.layout.list_activity, null);
        mErrorView = getLayoutInflater().inflate(R.layout.net_error_activity, null);
        setAbContentView(mContentView);
        mAppContext = getApplicationContext();
        initView();
    }

    private void initView() {
        AbTitleBar mAbTitleBar = getTitleBar();
        mAbTitleBar.setTitleText("用户管理");
        mAbTitleBar.setLogo(R.drawable.button_selector_back);
        mAbTitleBar.setTitleBarBackgroundColor(ContextCompat.getColor(this, R.color.orange));
        mAbTitleBar.setTitleTextMargin(10, 0, 0, 0);
        mAbTitleBar.setLogoLine(R.mipmap.line);
        View rightViewMore = mInflater.inflate(R.layout.title_right_add_btn, null);
        mAbTitleBar.addRightView(rightViewMore);
        Button mTitleRightBtn = rightViewMore.findViewById(R.id.title_right_add_btn);

        mData = new ArrayList<>();
        SwipeMenuListView mList = mContentView.findViewById(R.id.list_view);
        mAdapter = new MyBaseAdapter();
        mList.setAdapter(mAdapter);
        SwipeMenuCreator creator = menu -> {
            SwipeMenuItem editItem = new SwipeMenuItem(UserManagerQuery.this);
            editItem.setTitle("修 改");
            editItem.setBackground(new ColorDrawable(Color.rgb(0xC9, 0xC9, 0xCE)));
            editItem.setWidth(PixAndDpUtil.dp2px(80, UserManagerQuery.this.getApplicationContext()));
            editItem.setTitleSize(18);
            editItem.setTitleColor(Color.WHITE);
            menu.addMenuItem(editItem);

            SwipeMenuItem deleteItem = new SwipeMenuItem(UserManagerQuery.this);
            deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9, 0x3F, 0x25)));
            deleteItem.setWidth(PixAndDpUtil.dp2px(80, UserManagerQuery.this));
            deleteItem.setTitleSize(18);
            deleteItem.setIcon(R.mipmap.history_item_delete);
            deleteItem.setTitleColor(Color.WHITE);
            menu.addMenuItem(deleteItem);
        };
        mList.setMenuCreator(creator);
        mList.setOnMenuItemClickListener(this);
        Button mBtnTryAgain = mErrorView.findViewById(R.id.network_error_btn);
        mBtnTryAgain.setOnClickListener(v -> {
            setAbContentView(mContentView);
            getUsersInfo();
        });

        mTitleRightBtn.setOnClickListener(v -> {
            Intent intent = new Intent(UserManagerQuery.this, UserAdd.class);
            UserModel model = new UserModel();
            intent.putExtra("user", model);
            intent.putExtra("flag", "add");
            startActivityForResult(intent, ADDUSER);
        });

        mList.setOnItemClickListener((parent, view, position, id) -> {

        });
        loadFirst();
    }

    /**
     * 第一次加载
     */
    private void loadFirst() {
        AbLoadDialogFragment mDialogFragment = AbDialogUtil.showLoadDialog(UserManagerQuery.this,
                R.mipmap.ic_load, "查询中,请稍等...");
        mDialogFragment.setCancelable(false);
        mDialogFragment.setAbDialogOnLoadListener(this::getUsersInfo);
    }

    /**
     * 加载数据
     */
    private void getUsersInfo() {
        String methodName = "getUsersInfo";
        ArrayList<String> param = new ArrayList<>();
        ArrayList<String> value = new ArrayList<>();
        param.add("parentId");
        value.add(State.mAccount);
        Listener<String> listener = response -> {
            AbDialogUtil.removeDialog(UserManagerQuery.this);
            mData = JsonHelper.getJsonObjects(response);
            if (mData != null) {
                mAdapter.notifyDataSetChanged();
            }
        };

        ErrorListener errorListener = error -> {
            AbDialogUtil.removeDialog(UserManagerQuery.this);
            setAbContentView(mErrorView);
        };

        VolleyCallWebService webService = new VolleyCallWebService(methodName,
                param, value, listener, errorListener, Priority.NORMAL);
        VolleySingleton.getVolleyInstance(mAppContext).addRequest(webService);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            boolean result = data.getBooleanExtra("result", false);
            if (result) {
                getUsersInfo();
            }
        }
    }

    class MyBaseAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return mData.size();
        }

        @Override
        public Object getItem(int position) {
            return mData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.list_view_item_two_txt, null);
                holder = new ViewHolder();
                holder.img = convertView.findViewById(R.id.user_list_item_img);
                holder.account = convertView.findViewById(R.id.user_list_item_txt);
                holder.userName = convertView.findViewById(R.id.user_list_item_username);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            JSONObject obj = mData.get(position);
            holder.img.setImageResource(R.mipmap.user_ico);
            holder.account.setText("账    号:  " + obj.optString("账号"));
            holder.userName.setText("用户名:  " + obj.optString("用户名"));
            return convertView;
        }
    }

    class ViewHolder {
        private ImageView img;
        private TextView account;
        private TextView userName;
    }

    @Override
    public void onMenuItemClick(final int index, SwipeMenu arg1, int btnIndex) {
        final JSONObject obj = mData.get(index);
        if (btnIndex == 1) {
//            String account = obj.optString("账号");
//            delete(account, index);
            //删除用户前进行二次确认，以防误删
            new AlertDialog.Builder(UserManagerQuery.this, AlertDialog.THEME_HOLO_LIGHT)
                    .setTitle("提示")
                    .setCancelable(false)
                    .setMessage("是否确认删除该用户!")
                    .setPositiveButton("确定",
                            (arg0, arg112) -> {
                                String account = obj.optString("账号");
                                delete(account, index);

                            })
                    .setNegativeButton("取消",
                            (arg0, arg11) -> {
                            }).create().show();
        } else {

            UserModel model = new UserModel();
            model.setAccount(obj.optString("账号"));
            model.setName(obj.optString("用户名"));
            model.setPwd(obj.optString("密码"));
            model.setRight(obj.optString("权限"));
            model.setCompany(obj.optString("公司名称"));
            Intent i = new Intent(UserManagerQuery.this, UserAdd.class);
            i.putExtra("user", model);
            i.putExtra("flag", "update");
            int UPDATEUSER = 0X002;
            startActivityForResult(i, UPDATEUSER);
        }
    }

    /***
     * 删除账号
     */
    private void delete(String account, final int index) {
        String methodName = "deleteUser";
        ArrayList<String> param = new ArrayList<>();
        ArrayList<String> value = new ArrayList<>();
        param.add("account");
        value.add(account);
        Listener<String> listener = response -> {
            AbDialogUtil.removeDialog(UserManagerQuery.this);
            List<JSONObject> data = JsonHelper.getJsonObjects(response);
            if (data != null) {
                JSONObject obj = data.get(0);
                String memo = obj.optString("memo");
                if ("true".equals(obj.optString("result"))) {
                    mData.remove(index);
                    mAdapter.notifyDataSetChanged();
                } else {
                    Toast.makeText(UserManagerQuery.this, memo, Toast.LENGTH_LONG).show();
                }
            } else {
                Toast.makeText(UserManagerQuery.this, "操作失败!", Toast.LENGTH_LONG).show();
            }
        };

        ErrorListener errorListener = error -> {
            AbDialogUtil.removeDialog(UserManagerQuery.this);
            setAbContentView(mErrorView);
        };

        VolleyCallWebService webService = new VolleyCallWebService(methodName,
                param, value, listener, errorListener, Priority.NORMAL);
        VolleySingleton.getVolleyInstance(mAppContext).addRequest(webService);
    }

    @Override
    public void onBackPressed() {
        finish();
    }
}
